package com.example.reeman.ymfacedemo.readface.ui.icount;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.reeman.ymfacedemo.R;
import com.example.reeman.ymfacedemo.readface.base.BaseCameraActivity;
import com.example.reeman.ymfacedemo.readface.model.User;
import com.example.reeman.ymfacedemo.readface.util.DataSource;
import com.example.reeman.ymfacedemo.readface.util.TrackUtil;
import com.example.reeman.ymfacedemo.utils.LogUtils;

import java.io.File;
import java.util.List;

import dou.utils.BitmapUtil;
import dou.utils.DLog;
import mobile.ReadFace.YMFace;

/**
 * Created by ZJcan on 2017-10-14.
 */

public class RegisterFileActivity extends BaseCameraActivity implements View.OnClickListener {
    private Button addall;
    private TextView show_tip;
    public String register_path = "/sdcard/facemanager/lfw";
    private boolean canTest = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_file);
        addall = (Button) findViewById(R.id.addall);
        addall.setOnClickListener(this);
        show_tip = (TextView) findViewById(R.id.show_tip);
    }

    @Override
    protected void onResume() {
        super.onResume();
        File register_file = new File(register_path);
        if (!register_file.exists()) {
            DLog.d("register path is missing");
            show_tip.setText("facemanager文件夹不存在！");
            return;
        } else {
            File[] fileNames = register_file.listFiles();
            if (fileNames == null || fileNames.length < 1) {
                show_tip.setText("文件夹不存在文件！");
                return;
            }
        }
        show_tip.setText("ok,等待提交训练,只会训练图片文件。以文件名标识！");
        canTest = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void drawAnim(List<YMFace> faces, SurfaceView draw_view, float scale_bit, int cameraId, String fps) {

    }

    @Override
    protected List<YMFace> analyse(byte[] bytes, int iw, int ih) {
        return null;
    }

    @Override
    public void onClick(View v) {
        if (canTest) {
            new Thread() {
                @Override
                public void run() {
                    startTest();
                }
            }.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void startTest() {
        File register_file = new File(register_path);
        if (!register_file.exists()) {
            DLog.d("register path is missing");
            return;
        }
        test(register_file, true);
    }

    private void test(File test_file, boolean register) {
        if (register) {
            File[] fileNames = test_file.listFiles();
            for (int i = 0; i < fileNames.length; i++) {
                //数个文件夹
                File dic = fileNames[i];

                LogUtils.e("文件夹名称 1   ====>  " + dic.getName());
                if (dic.isDirectory()) {
                    File[] images = dic.listFiles();
                    int personId = -111;
                    boolean isAdd = false;
                    for (int j = 0; j < images.length; j++) {
                        File image = images[j];
                        LogUtils.e("文件夹名称 2   ====>  " + dic.getName());
                        if (image.getName().contains(".JPG") || image.getName().contains(".jpg")
                                || image.getName().contains(".png") || image.getName().contains(".jpeg")
                                || image.getName().contains(".bmp")) {
                            if (j == 0 || !isAdd) {
                                personId = addPerson(image);
                                if (personId > 0) {
                                    isAdd = true;
                                    Bitmap file_logo = BitmapUtil.getSmallBitmap(image.getPath(), 96, 96);
                                    BitmapUtil.saveBitmap(file_logo, mContext.getCacheDir() + "/" + personId + ".jpg");
                                }
                            } else {
                                updatePerson(image, personId);
                            }
                        }
                    }
                    if(isAdd){
                        int gender_score = faceTrack.getGender(0);
                        int gender_confidence = faceTrack.getGenderConfidence(0);
                        String gender = " ";
                        if (gender_confidence >= 90)
                            gender = faceTrack.getGender(0) == 0 ? "F" : "M";
                        String score = gender_score + "";
                        String age = String.valueOf(TrackUtil.computingAge(faceTrack.getAge(0)));
                        String name = dic.getName();
                        DLog.d("add Face 1 " + personId + " name :" + name + " gender: " + gender);
                        addNewPerson(personId, name, gender, age, score);
                    }
                }
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    show_tip.setText("ok,已经读取完全部数据！");
                    addall.setEnabled(false);
                }
            });
        }
    }

    private void addNewPerson(int personId, String name, String gender, String age, String score) {
        if (personId > 0) {
            User user = new User("" + personId, name, age, gender);
            user.setScore(score);
            DataSource dataSource = new DataSource(mContext);
            dataSource.insert(user);
        } else {
            DLog.d("添加人脸失败！");
        }
    }

    private int addPerson(File image) {
        if (detect(image)) {
            int personId = faceTrack.addPerson(0);
            DLog.d(image.getName() + " add : " + personId + " con ：" + faceTrack.getRecognitionConfidence());
            return personId;
        }
        return -111;
    }

    private void updatePerson(File image, int personId) {
        if (detect(image)) {
            int updateResult = faceTrack.updatePerson(personId, 0);
            DLog.d(image.getName() + " update : " + updateResult + " con ：" + faceTrack.getRecognitionConfidence());
        }
    }

    Bitmap targetBitmap;

    private boolean detect(File image) {
        if (targetBitmap != null && !targetBitmap.isRecycled()) targetBitmap.recycle();
        targetBitmap = BitmapUtil.decodeScaleImage(image.getAbsolutePath(), 1000, 1000);
        List<YMFace> ymFaces = faceTrack.detectMultiBitmap(targetBitmap);

        if (ymFaces != null && ymFaces.size() != 0) {
            int personId1 = faceTrack.identifyPerson(0);
            if (personId1 < 0) {
                return true;
            }
        }
        return false;
    }
}
